﻿using CloudStorage_Backend.model;
using CloudStorage_Backend.service;
using CloudStorage_Backend.utils;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using Microsoft.AspNetCore.Authorization;

namespace CloudStorage_Backend.controller
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly FileService fileService;

        private static IWebHostEnvironment _webHostEnvironment;

        public FileController(FileService fileService, IWebHostEnvironment webHostEnvironment)
        {
            this.fileService = fileService;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload")]
        [Authorize]
        public ResponseResult<string> UploadFile() {
            var file = Request.Form.Files[0];
            Request.EnableBuffering();

            IFormCollection collection = Request.Form;
            FileChunkInfoVO info = new FileChunkInfoVO
            {
                UserName = collection["userName"],
                DestinationPath = collection["destinationPath"],
                FlowChunkNumber = Convert.ToInt32(collection["flowChunkNumber"]),
                FlowChunkSize = Convert.ToInt32(collection["flowChunkSize"]),
                FlowTotalSize = Convert.ToInt32(collection["flowTotalSize"]),
                FlowIdentifier = collection["flowIdentifier"],
                FlowFileName = collection["flowFileName"],
                FlowRelativePath = collection["flowRelativePath"],
                FlowTotalChunks = Convert.ToInt32(collection["flowTotalChunks"])
            };
            fileService.UploadFile(file, info, collection["userName"], _webHostEnvironment.ContentRootPath);
            return ResponseResult<string>.Ok();
        }

        [HttpGet("upload")]
        [Authorize]
        public ActionResult<ResponseResult<string>> GetChunk(string userName, int flowChunkNumber, int flowTotalChunks,
              int flowChunkSize, int flowTotalSize, string flowIdentifier, string flowFileName,
              string flowRelativePath, string? destinationPath)
        {
            if (destinationPath == null)
            {
                destinationPath = "";
            }
            FileChunkInfoVO info = new FileChunkInfoVO
            {
                UserName = userName,
                FlowChunkNumber = flowChunkNumber,
                FlowTotalChunks = flowTotalChunks,
                FlowChunkSize = flowChunkSize,
                FlowTotalSize = flowTotalSize,
                FlowIdentifier = flowIdentifier,
                FlowFileName = flowFileName,
                FlowRelativePath = flowRelativePath,
                DestinationPath = destinationPath
            };
            if(FileHelper.testFile(info, _webHostEnvironment.ContentRootPath))
            {
                return ResponseResult<string>.Ok();
            } else
            {
                return NoContent();
            }
        }

        /// <summary>
        /// 获得文件列表
        /// </summary>
        /// <param name="path"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [Authorize]
        public ResponseResult<List<FileInfoVO>> GetFileList(string userName, string? path)
        {
            if(path == null) {
                path = "";
            }
            return ResponseResult<List<FileInfoVO>>.Ok(fileService.GetFileList(path, userName, _webHostEnvironment.ContentRootPath));
        }

        /// <summary>
        /// 搜索文件
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="path"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet("search")]
        [Authorize]
        public ResponseResult<List<FileInfoVO>> SearchFile(string userName, string? path, string? keyword)
        {
            if(path == null)
            {
                path = "";
            }
            if(keyword == null)
            {
                keyword = "";
            }
            return ResponseResult<List<FileInfoVO>>.Ok(fileService.SearchFile(userName, _webHostEnvironment.ContentRootPath, path, keyword));
        }

        /// <summary>
        /// 新建文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpPost("newFolder")]
        [Authorize]
        public ResponseResult<string> NewFolder(string path, string userName)
        {
            fileService.CreateFolder(path, userName, _webHostEnvironment.ContentRootPath);
            return ResponseResult<string>.Ok();
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="paths"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        [Authorize]
        public ResponseResult<string> DeleteFiles([FromQuery]string userName, [FromBody]List<string> paths)
        {
            fileService.DeleteFiles(userName, _webHostEnvironment.ContentRootPath, paths);
            return ResponseResult<string>.Ok();
        }

        /// <summary>
        /// 复制粘贴文件
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="destinationPath"></param>
        /// <param name="filePaths"></param>
        /// <returns></returns>
        [HttpPost("copy")]
        [Authorize]
        public ResponseResult<string> CopyFiles([FromQuery]string userName, [FromQuery]string destinationPath, [FromBody]List<string> filePaths)
        {
            fileService.CopyFiles(userName, _webHostEnvironment.ContentRootPath, destinationPath, filePaths);
            return ResponseResult<string>.Ok();
        }

        /// <summary>
        /// 剪切粘贴文件
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="destinationPath"></param>
        /// <param name="filePaths"></param>
        /// <returns></returns>
        [HttpPost("cut")]
        [Authorize]
        public ResponseResult<string> CutFiles([FromQuery] string userName, [FromQuery] string destinationPath, [FromBody] List<string> filePaths)
        {
            fileService.CutFiles(userName, _webHostEnvironment.ContentRootPath, destinationPath, filePaths);
            return ResponseResult<string>.Ok();
        }

        /// <summary>
        /// 读取文本文件
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="filePath"></param>
        /// <param name="pageNum"></param>
        /// <returns></returns>
        [HttpGet("readText")]
        [Authorize]
        public ResponseResult<string> ReadTextFile([FromQuery]string userName, [FromQuery]string filePath, [FromQuery]int pageNum)
        {
            return ResponseResult<string>.Ok(fileService.ReadTextFile(userName, _webHostEnvironment.ContentRootPath, filePath, pageNum));
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pictPath"></param>
        /// <returns></returns>
        [HttpGet("readPict")]
        [Authorize]
        public IActionResult ReadPict([FromQuery]string userName, [FromQuery]string pictPath)
        {
            string path = fileService.ReadPict(userName, _webHostEnvironment.ContentRootPath, pictPath);
            FileInfo info = new FileInfo(path);
            FileStream stream = info.OpenRead();
            var resp = new FileStreamResult(stream, "image/*");
            return resp;
        }

    }
}
